package lesson3.api.helpers;

import static lesson3.api.ApplicationManager.SITE_URL;

import java.util.Map;

import lesson3.api.ApplicationManager;
import lesson3.api.models.LocatorModel;
import lesson3.pages.locators.site.ForumLocators;
import lesson3.pages.locators.site.RedmineLocators;
import lesson3.pages.locators.site.SiteLocators;

import org.openqa.selenium.By;

public class LocatorHelper
{
	// Application manager instance
	private final ApplicationManager app;

	public LocatorHelper(ApplicationManager p_app)
	{
		app = p_app;
	}

	public By getLocator(String p_name)
	{
		// Get list of locators
		Map<String, LocatorModel> locators = getSiteLocators().getPageLocators().getLocators();
		// Extract type and value of locator
		String type = locators.get(p_name).getType();
		String value = locators.get(p_name).getValue();
		// Get locator by type
		By locator = getLocatorByType(type, value);

		return locator;
	}

	public By getLocatorByType(String p_type, String p_value)
	{
		if (p_type.isEmpty() || p_value.isEmpty())
		{
			return null;
		}
		else if (p_type.equals("id"))
		{
			// Return the locator by 'id'
			return By.id(p_value);
		}
		else if (p_type.equals("name"))
		{
			// Return the locator by 'name'
			return By.name(p_value);
		}
		else if (p_type.equals("class"))
		{
			// Return the locator by 'class'
			return By.className(p_value);
		}
		else if (p_type.equals("css"))
		{
			// Return the locator by 'css'
			return By.cssSelector(p_value);
		}
		else if (p_type.equals("xpath"))
		{
			// Return the locator by 'xpath'
			return By.xpath(p_value);
		}
		else if (p_type.equals("link_text"))
		{
			// Return the locator by 'link text'
			return By.linkText(p_value);
		}
		else
		{
			return null;
		}
	}

	public String getPageURL(String p_page)
	{
		// Get list of locators
		Map<String, LocatorModel> locator = getSiteLocators().getPageLocators().getLocators();
		// Get value - page URL
		String page = locator.get("page").getValue();

		return page;
	}

	private SiteLocators getSiteLocators()
	{
		if (SITE_URL.contains("redmine"))
		{
			return new RedmineLocators(app);
		}
		else if (SITE_URL.contains("kb.mgroup"))
		{
			return new ForumLocators(app);
		}

		return null;
	}
}
